package com.wondersgroup.fjzlpt.console.config;

import java.lang.reflect.Method;

import com.quick.framework.boot.repository.nosql.redis.FastJson2JsonRedisSerializer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Value("${console.redis.timeoutSecond}")
	private int timeoutSecond;

	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			protected final Log logger = LogFactory.getLog(getClass());
			@Override
			public Object generate(Object target, Method method,
								   Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append("."+method.getName());
				for (Object obj : params) {
					if(null != obj)
						sb.append(obj.toString());
				}
				logger.debug("获取缓存key:" + sb.toString());
				return sb.toString();
			}
		};
	}

	@SuppressWarnings("rawtypes")
	@Bean
	public CacheManager cacheManager(RedisTemplate redisTemplate) {
		RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
		// 设置缓存过期时间
		 rcm.setDefaultExpiration(timeoutSecond);//秒
		return rcm;
	}

	@Bean
	@SuppressWarnings("rawtypes")
	public RedisSerializer fastJson2JsonRedisSerializer() {
		return new FastJson2JsonRedisSerializer<Object>(Object.class);
	}

	@Bean
	public RedisTemplate<String, String> redisTemplate(
			RedisConnectionFactory factory, RedisSerializer fastJson2JsonRedisSerializer) {
		StringRedisTemplate template = new StringRedisTemplate(factory);
		template.setValueSerializer(fastJson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}

}
